# -*- coding:utf-8 -*-
__author__ = 'lixin'
import os
import time
import datetime
import sys
import stat
import ConfigParser
try:
    import picamera
except:
    print('Can not find Module:picamera')
    #exit()

#加载配置文件
root=os.path.split(os.path.realpath(__file__))[0]
savePath=os.path.join(root,'img/')
picSizeSmall=(640,480)
picSizeBig=(1280,720)
interval=30
saeAccessKey=''
saeSecretKey=''
saeBucket=''
if not os.path.exists(savePath):
    os.mkdir(savePath)
if os.path.exists(os.path.join(root,'fragment.conf')):
    cf=ConfigParser.ConfigParser()
    cf.read(os.path.join(root,'fragment.conf'))
    _smallConfig=cf.get("setting","pic-size-small")
    _bigConfig=cf.get('setting',"pic-size-big")
    picSizeSmall=(int(_smallConfig.split('*')[0]),int(_smallConfig.split('*')[1]))
    picSizeBig=(int(_bigConfig.split('*')[0]),int(_bigConfig.split("*")[1]))
    interval=int(cf.get("setting","interval"))
    saeAccessKey=cf.get("sae",'accessKey')
    saeSecretKey=cf.get("sae",'secretKey')
    saeBucket=cf.get('sae','bucket')
    if len(saeAccessKey)>0 and len(saeSecretKey)>0 and len(saeBucket)>0:
        try:
            import sinastorage
            from sinastorage.bucket import SCSBucket
        except Exception ,ex:
            print("Not find Module sinastorage\nPlease pip install scs-sdk")
            saeAccessKey=''
            saeSecretKey=''
            saeBucket=''

def run():
    while True:
        with picamera.PiCamera() as camera:
            camera.resolution=picSizeBig
            camera.start_preview()
            #camera warm-up time
            time.sleep(2)
            # camera.capture('xx.jpg',resize=(1,2))
            timeText=datetime.datetime.now().strftime('%Y-%m-%d-%H:%M:%S')
            camera.annotate_text=timeText

            camera.capture(os.path.join(savePath,timeText+".jpg"))
            camera.capture(os.path.join(savePath,timeText+"_small.jpg"),resize=picSizeSmall)
            if len(saeAccessKey)>0 and len(saeSecretKey) and len(saeBucket):
                sinastorage.setDefaultAppInfo(saeAccessKey, saeSecretKey)
                s=SCSBucket(saeBucket)
                s.putFile("RPI/"+datetime.datetime.now().strftime("%Y-%m-%d/")+timeText+"_small.jpg",os.path.join(savePath,timeText+"_small.jpg"))
            print ('capture pic\n')
            time.sleep(interval)

if __name__ =="__main__":
    if len(sys.argv)>1 and sys.argv[1]=="install":
        f=open('/etc/init.d/RPIFragment.sh','w')
        f.write('''
#!/bin/sh
### BEGIN INIT INFO
# Provides:          RPIFragment.sh
# Required-Start:    $local_fs $remote_fs $network $syslog
# Required-Stop:     $local_fs $remote_fs $network $syslog
# Default-Start:     2 3 4
# Default-Stop:
# Short-Description: starts the RPIFragment daemon
# Description:       starts RPIFragment using start-stop-daemon
### END INIT INFO
        ''')
        f.write('python '+os.path.join(root,sys.argv[0])+'\n')
        f.close()
        os.chmod('/etc/init.d/RPIFragment.sh',stat.S_IRWXU|stat.S_IRWXG|stat.S_IXOTH|stat.S_IRWXG)
        os.system('update-rc.d RPIFragment.sh start 999 2 3 4 ')
        pass
    elif len(sys.argv)>1 and sys.argv[1]=="remove":
        os.system('sudo update-rc.d RPIFragment.sh remove')
        os.remove('/etc/init.d/RPIFragment.sh')
        print("remove ok")
        pass
    else:
        run()